package code;

public class BaseController {

	private IUI UI;
	private TCPConnector connector;
	private WeightController weight;
	private Thread UIThread, TCPThread;
	private boolean nextIsRM20;

	public BaseController(IUI UI, TCPConnector connecter, WeightController weight){

		this.UI = UI;
		this.connector = connecter;
		this.weight = weight;
		TCPThread = new Thread(connector, "TCPThread");
		UIThread  = new Thread(UI, "UIThread");
		TCPThread.start();
		UIThread.start();	

	}

	public void listenForInput() {

		String input = null;
		UI.updateScreen(weight);
		while (input == null) {
			
			input = UI.getInput();
			
			if (input == null)
			{
				input = connector.getReceivedData();	
			}
			
		}
		
		processInputMessage(input);
		
		synchronized (UI) {
			UI.notify();
		}
		listenForInput();

	}

	public void processInputMessage(String input){

		if(input.equals("Q")){
			UIThread.interrupt();
			TCPThread.interrupt();
			System.exit(0);	
		}

		// Should pass on input to look for intern commands before sending on...
		
		if (!nextIsRM20)
		{
			String output = weight.parseCommand(input);
			
			if (output.equals("RM20 B")){
							
				UI.updateScreen(weight);
				connector.send(output);
				output = UI.respondRM20();	
				nextIsRM20 = true;
								
			}
				
			if (output != null)
			{
				connector.send(output);
			}
		}
		else
		{
			nextIsRM20 = false;
			weight.updateDisplay();
		}
		
	}
}